package com.cty.service.impl;

import com.cty.mapper.FeelMapper;
import com.cty.mapper.ImgMapper;
import com.cty.pojo.Feel;
import com.cty.pojo.Img;
import com.cty.service.FeelService;
import com.cty.utils.FtpUtil;
import com.cty.utils.IDUtils;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Auther: cty
 * @Date: 2020/4/5 22:36
 * @Description:
 * @version: 1.0
 */
@Service
public class FeelServiceImpl implements FeelService {
    Logger log = Logger.getLogger(FeelServiceImpl.class);

    @Resource
    private FeelMapper feelMapper;
    @Resource
    private ImgMapper imgMapper;

    @Value("${ftpclient.host}")
    private String host;
    @Value("${ftpclient.port}")
    private int port;
    @Value("${ftpclient.username}")
    private String username;
    @Value("${ftpclient.password}")
    private String password;
    @Value("${ftpclient.basePath}")
    private String basePath;
    @Value("${ftpclient.filepath}")
    private String filePath;

    @Override
    public Map<String, Object> upload(MultipartFile imgFile) throws IOException {
        String fileName = UUID.randomUUID()+imgFile.getOriginalFilename().substring(imgFile.getOriginalFilename().lastIndexOf("."));
        log.info("将上传文件："+imgFile.getOriginalFilename());
        boolean result =  FtpUtil.uploadFile(host, port, username, password, basePath, filePath, fileName, imgFile.getInputStream());
        Map<String, Object> map = new HashMap<>();
        if(result){
            map.put("error", 0);
            map.put("url", "http://192.168.238.128/"+fileName);
        }else {
            map.put("error", 1);
            map.put("message", "图片上传失败！！！");
        }
        return map;
    }

    @Override
    public int insert(Feel feel, List<String> imgs) {
        Long fid = IDUtils.genItemId();
        feel.setId(fid);
        int index = this.feelMapper.insert(feel);  // 插入时所有属性都要自定义赋值
        if(index>0){
            for(String img:imgs){
                Img image = new Img();
                image.setPath(img);
                image.setFid(fid);
                index += this.imgMapper.insertSelective(image);  // 只插入非空的属性
            }
            if(index==imgs.size()+1){
                return 1;
            }
        }
        return 0;
    }
}
